extends Node

@onready var player_scene = preload("res://Player/player.tscn")
@onready var flag: Node2D = $Flag
@onready var level_complete_scene = preload("res://UI/level_complete.tscn")
@onready var PAUSE_MENU = preload("res://UI/pause_menu.tscn")

var born_position: Vector2 = Vector2.ZERO
var now_player: Player = null
var player_group
var player_nodes
var player_death:PlayerDeath = null
var scores: int = 0
signal passed_level

func _ready() -> void:
	# 连接通关旗帜
	flag.connect("player_won", on_player_won)
	player_group = get_tree().get_nodes_in_group("players")
	player_nodes = get_tree().get_nodes_in_group("player_nodes")[0]
	if (player_group.size() > 0):
		now_player = player_group[0]
		born_position = now_player.global_position

func _unhandled_input(event: InputEvent) -> void:
	if (event.is_action_pressed("pause")):
		var pause_menu := PAUSE_MENU.instantiate()
		add_child(pause_menu)
		
# 进入下一关
func on_player_won():
	var level_complete_instance = level_complete_scene.instantiate()
	add_child(level_complete_instance)
	now_player.on_passed_level()
	
func _process(delta: float) -> void:
	player_group = get_tree().get_nodes_in_group("players")
	var death_group = get_tree().get_nodes_in_group("player_death")


func on_death_ended():
	var new_player: Player = player_scene.instantiate()	# 当死亡动画播放结束后创建一个新的玩家
	new_player.global_position = born_position
	now_player = new_player
	player_nodes.add_child(new_player)
